# -*- coding: utf-8 -*-
import os
from time import sleep
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from pysql import  *
import shutil

global page;
class downDocFile:
    #account 爬取试卷的账号
    #pernumOfaccount 每个账号抓取的数量
    def __init__(self,workdir,account,pernumOfaccount):
         #爬取账号列表('用户名',密码)
         self.account=account;
         self.pernumOfaccount=pernumOfaccount;
         self.workdir=workdir;
         self.mysqloper=mysqlOper();

    def getdriver(self,downloadpath):
        options = webdriver.ChromeOptions()
        prefs = {'profile.default_content_settings.popups': 0, 'download.default_directory': downloadpath}
        options.add_experimental_option('prefs', prefs)
        driver = webdriver.Chrome(chrome_options=options);

        username=self.account[0];
        password=self.account[1];
        driver.get('https://sso.zxxk.com/login')
        WebDriverWait(driver, 5).until(EC.visibility_of(driver.find_element(by=By.ID, value='CommonLogin')))
        input_name = driver.find_element_by_name('username');
        input_name.send_keys(username);
        input_password = driver.find_element_by_name('password');
        input_password.send_keys(password);
        input_submit = driver.find_element_by_id('CommonLogin');
        input_submit.click();
        return driver;

    #退出登录
    def quitLogin(driver):
        quit=driver.find_element_by_xpath("//div[@class='land']/a[2]");
        action = ActionChains(driver);
        action.move_to_element(quit).perform()
        quit.click();
    #日志记录
    def log(self):
        global page;
        global currentnum;
        global totalcount;
        print('current download page=%d,currentnum=%d,totalcount=%d' %(page,currentnum,totalcount));

    def opennewtab(self,driver,url):
        js = 'window.open("{}");'.format(url)
        driver.execute_script(js)
        handles = driver.window_handles

        print handles  # 输出句柄集合
        for handle in handles:
            if handle != driver.current_window_handle:
                print 'switch to ', handle
                driver.switch_to_window(handle)
                print driver.current_window_handle  #
                break
        return driver.current_window_handle;

    def download(self,driver,xkwid,ppath,downurl):
        tabno=self.opennewtab(driver,downurl)
        WebDriverWait(driver, 50).until(EC.visibility_of(driver.find_element(by=By.ID, value='btnSoftDownload')))
        try:
            driver.find_element_by_id('btnSoftDownload').click();
            sleep(1000)
            #将文件
            self.mvTempDownToDir(ppath,xkwid);
        except Exception as e:
            print  e;

    def mvTempDownToDir(self,ppath,file):
        temppath=os.path.join(self.workdir,'temp');
        files=os.listdir(temppath)
        if(len(files)==0 or len(files>1)):
            return;
        srcpath=os.path.join(temppath,files[0]);
        lastprefix=files[0][srcpath.index('.')]
        shutil.move(srcpath,ppath);

    def getDriver(self,downloadpath):
        options = webdriver.ChromeOptions()
        prefs = {'profile.default_content_settings.popups': 0, 'download.default_directory': downloadpath}
        options.add_experimental_option('prefs', prefs)
        driver = webdriver.Chrome(chrome_options=options);
        return driver;

    def downdocfiles(self):
        try:
            downpath=os.path.join(workdir,'temp');
            self.temppath=downpath;
            if(not os.path.exists(downpath)):
                os.makedirs(downpath);
            driver=self.getdriver(downpath)
            #从数据库获取N条数据
            datas=self.mysqloper.getDownUrl(self.pernumOfaccount)
            self.bookinfo={};
            for d in datas:
                #创建目录
                xkwid = d['xkwid']
                papername=d['papername']
                xkwid=xkwid[1:]
                downurl = d['downurl']
                self.bookinfo[papername]=d;
                ppath=os.path.join(self.workdir,xkwid);
                if(not os.path.exists(ppath)):
                    os.makedirs(ppath);
                self.download(driver,xkwid,ppath,downurl);
                driver.close();
                driver.switch_to_window((driver.window_handles)[0])
        except Exception as e:
            raise e;
            driver.quit();
            toScrapy();
account=('18311033087','1234567')
workdir='/work/temp/xuekewang'
dc=downDocFile(workdir,account,10);
dc.downdocfiles();




